package com.ysb.config;

<#if rabbitMQ>
import com.ysb.config.rabbit.consumer.RabbitConsumerConfig;
import com.ysb.constant.RabbitConstants;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
</#if>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author scaffolding
 * @since ${dateTime}
 */
@Configuration
public class ExecutorConfig {

    /**
     * 公共线程池
     */
    @Bean
    public ThreadPoolTaskExecutor commonExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(30);
        executor.setMaxPoolSize(30);
        executor.setQueueCapacity(2000);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("commonExecutor-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }

<#if rabbitMQ>
    /**
     * 消息消费者线程池
     */
    @Bean
    @ConditionalOnBean(RabbitConsumerConfig.class)
    public ThreadPoolTaskExecutor messageConsumerExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 用于consumer线程，禁止使用阻塞队列
        executor.setCorePoolSize(RabbitConstants.MAX_CONSUMERS);
        executor.setMaxPoolSize(RabbitConstants.MAX_CONSUMERS);
        executor.setThreadNamePrefix("messageConsumerExecutor-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }
</#if>
}
